package main

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
	"net/http"
	"strings"
	"time"
)

func main() {
	router := gin.Default()

	// 设置模板文件路径
	router.LoadHTMLFiles("templates/index.html")

	// GET 请求用于显示表单
	//router.GET("/", func(c *gin.Context) {
	//	c.HTML(http.StatusOK, "index.html", nil)
	//})

	// POST 周末秒杀
	router.POST("/kill", func(c *gin.Context) {
		var data struct {
			Sid       string `json:"sid"`
			PrizeId   string `json:"prizeId"`
			Timestamp string `json:"timestamp"`
		}
		if err := c.ShouldBindJSON(&data); err != nil {
			panic(err)
		}
		// 定义时间格式
		layout := "2006-01-02 15:04:05.999999999"

		// 解析时间字符串
		t, err := time.Parse(layout, data.Timestamp)
		if err != nil {
			fmt.Println("解析时间失败:", err)
			return
		}
		location, err := time.LoadLocation("Asia/Shanghai")
		if err != nil {
			fmt.Println("加载时区失败:", err)
			return
		}
		t = t.In(location)

		fmt.Println(t)
		now := time.Now()
		hourInt := 10
		minInt := 00
		sec := 00
		nsec := 50
		nsec = nsec * 1e6
		// 指定时间
		specifiedTime := time.Date(now.Year(), now.Month(), now.Day(), hourInt, minInt, sec, nsec, now.Location())
		if t.After(specifiedTime) {
			// 处理表单数据
			c.JSON(http.StatusInternalServerError, gin.H{
				"date": "时间输入错误",
			})
			panic("时间输入错误")
		}
		fmt.Println(specifiedTime)
		// 计算剩余时间
		timeToWait := specifiedTime.Sub(t)
		// 等待剩余时间
		time.Sleep(timeToWait)
		// POST 秒杀test
		LianTongKill(c, data.Sid, data.PrizeId)
	})
	// POST 周五秒杀
	router.POST("/friday/kill", func(c *gin.Context) {
		var data struct {
			Sid       string `json:"sid"`
			PrizeId   string `json:"prizeId"`
			Timestamp string `json:"timestamp"`
		}
		if err := c.ShouldBindJSON(&data); err != nil {
			panic(err)
		}
		// 定义时间格式
		layout := "2006-01-02 15:04:05.999999999"

		// 解析时间字符串
		t, err := time.Parse(layout, data.Timestamp)
		if err != nil {
			fmt.Println("解析时间失败:", err)
			return
		}
		//location, err := time.LoadLocation("Asia/Shanghai")
		//if err != nil {
		//	fmt.Println("加载时区失败:", err)
		//	return
		//}
		//t = t.In(location)

		fmt.Println(t)
		now := time.Now()
		hourInt := 9
		minInt := 00
		sec := 00
		nsec := 00
		nsec = nsec * 1e6
		// 指定时间
		specifiedTime := time.Date(now.Year(), now.Month(), now.Day(), hourInt, minInt, sec, nsec, now.Location())
		if t.After(specifiedTime) {
			// 处理表单数据
			c.JSON(http.StatusInternalServerError, gin.H{
				"date": "时间输入错误",
			})
			panic("时间输入错误")
		}
		fmt.Println(specifiedTime)
		//timestamp := c.PostForm("timestamp")
		//// 定义时间布局
		//layout := "2006-01-02T15:04:05Z"
		//parsedTime, err := time.Parse(layout, timestamp)
		//if err != nil {
		//	fmt.Println("解析错误:", err)
		//	return
		//}
		// 计算剩余时间
		timeToWait := specifiedTime.Sub(t)
		// 等待剩余时间
		time.Sleep(timeToWait)
		sid := c.PostForm("fsid")
		exchId := c.PostForm("exchId")
		// POST 秒杀test
		LianTongFridayKill(c, sid, exchId)
	})

	// POST 周末查询
	router.POST("/killList", func(c *gin.Context) {
		LianTongKillList(c)
	})
	// POST 周五查询
	router.POST("/friday/list", func(c *gin.Context) {
		LianTongKillFridayList(c)
	})
	// POST 周末预测
	router.POST("/killTest", func(c *gin.Context) {
		LianTongKill(c, "1", "1")
	})
	// POST 周末预测
	router.POST("/friday/killTest", func(c *gin.Context) {
		LianTongFridayKill(c, "1", "1")
	})
	router.Run(":1234") // 在端口8080上启动服务
}

// LianTongKill 周末秒杀
func LianTongKill(c *gin.Context, sids string, prizeId string) {
	//开始时间
	nowss := time.Now()
	fmt.Println(nowss)
	sid := strings.Split(sids, ",")
	url := fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenterSeckill/exchangeOperate?sid=%s&actcode=welfareCenterSeckill&prizeId=%s", sid[0], prizeId)
	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	// 获取完成时间时间
	nows := time.Now()
	fmt.Println(nows)
	// 计算差时间
	timeToWait := nowss.Sub(nows)
	fmt.Println(timeToWait)
	defer resp.Body.Close()
	now := time.Now()
	// 格式化当前时间和指定时间
	nowFormatted := now.Format("2006-01-02 15:04:05.000")
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	var responseBody ResponseBody
	err = json.Unmarshal(body, &responseBody)
	if err != nil {
		log.Fatalf("Error unmarshaling response body: %v", err)
	}
	// 打印响应状态码和响应体
	fmt.Printf("Response Status: %s\n", resp.Status)
	fmt.Printf("Response Body: %s\n", body)
	// 创建 map 并填充键值对
	resultMap := make(map[string]interface{})
	resultMap["status"] = "success"
	resultMap["message"] = "秒杀成功"
	resultMap["Response Status:"] = resp.Status
	resultMap["Response Body:"] = responseBody
	resultMap["当前时间"] = nowFormatted
	if len(sid) > 1 {
		// 第二次发送GET请求
		resp2, err2 := http.Get(fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenterSeckill/exchangeOperate?sid=%s&actcode=welfareCenterSeckill&prizeId=%s", sid[1], prizeId))
		if err2 != nil {
			log.Fatalf("Error sending request: %v", err2)
		}
		defer resp2.Body.Close()
	}
	//defer resp2.Body.Close()
	// 将 map 转换为 JSON 字符串
	jsonResult, err := json.Marshal(resultMap)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal JSON"})
		return
	}

	// 渲染结果到页面
	c.HTML(http.StatusOK, "index.html", gin.H{
		"RBody": string(jsonResult),
	})
}

// LianTongFridayKill 周五秒杀
func LianTongFridayKill(c *gin.Context, sids string, exchId string) {
	//开始时间
	nowss := time.Now()
	fmt.Println(nowss)
	sid := strings.Split(sids, ",")
	url := fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenter/exchangeOperate?sid=%s&exchId=%s&actcode=welfareCenter", sid[0], exchId)
	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	// 获取完成时间时间
	nows := time.Now()
	fmt.Println(nows)
	// 计算差时间
	timeToWait := nowss.Sub(nows)
	fmt.Println(timeToWait)
	defer resp.Body.Close()
	now := time.Now()
	// 格式化当前时间和指定时间
	nowFormatted := now.Format("2006-01-02 15:04:05.000")
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	var responseBody ResponseBody
	err = json.Unmarshal(body, &responseBody)
	if err != nil {
		log.Fatalf("Error unmarshaling response body: %v", err)
	}
	// 打印响应状态码和响应体
	fmt.Printf("Response Status: %s\n", resp.Status)
	fmt.Printf("Response Body: %s\n", body)
	// 创建 map 并填充键值对
	resultMap := make(map[string]interface{})
	resultMap["status"] = "success"
	resultMap["message"] = "秒杀成功"
	resultMap["Response Status:"] = resp.Status
	resultMap["Response Body:"] = responseBody
	resultMap["当前时间"] = nowFormatted
	if len(sid) > 1 {
		// 第二次发送GET请求
		resp2, err2 := http.Get(fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenter/exchangeOperate?sid=%s&exchId=%s&actcode=welfareCenter", sid[1], exchId))
		if err2 != nil {
			log.Fatalf("Error sending request: %v", err2)
		}
		defer resp2.Body.Close()
	}
	//defer resp2.Body.Close()
	// 将 map 转换为 JSON 字符串
	jsonResult, err := json.Marshal(resultMap)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to marshal JSON"})
		return
	}

	// 渲染结果到页面
	c.HTML(http.StatusOK, "index.html", gin.H{
		"RBody": string(jsonResult),
	})
}

type ResponseBody struct {
	ResultCode string      `json:"resultCode"`
	ResultMsg  string      `json:"resultMsg"`
	Data       interface{} `json:"data"`
}

// LianTongKillList 查询
func LianTongKillList(c *gin.Context) {
	sid := c.PostForm("sid")
	url := fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenterSeckill/loadInit?sid=%s&actcode=welfareCenterSeckill", sid)

	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()
	now := time.Now()
	// 格式化当前时间和指定时间
	nowFormatted := now.Format("2006-01-02 15:04:05.000")
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	m := make(map[string]interface{})
	err = json.Unmarshal(body, &m)
	if err != nil {
		log.Fatalf("Error unmarshaling response body: %v", err)
	}
	// 打印响应状态码和响应体
	fmt.Printf("Response Status: %s\n", resp.Status)
	fmt.Printf("Response Body: %s\n", body)
	// 处理表单数据
	c.JSON(http.StatusOK, gin.H{
		"Response Body:": m,
		"当前时间":           nowFormatted,
	})
}

// LianTongKillFridayList 查询
func LianTongKillFridayList(c *gin.Context) {
	sid := c.PostForm("sid")
	url := fmt.Sprintf("https://weixin.linktech.hk/lv-apiaccess/welfareCenter/exchangeInit?actcode=welfareCenter&sid=%s", sid)

	// 发送GET请求
	resp, err := http.Get(url)
	if err != nil {
		log.Fatalf("Error sending request: %v", err)
	}
	defer resp.Body.Close()
	now := time.Now()
	// 格式化当前时间和指定时间
	nowFormatted := now.Format("2006-01-02 15:04:05.000")
	// 读取响应体
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Error reading response body: %v", err)
	}
	m := make(map[string]interface{})
	err = json.Unmarshal(body, &m)
	if err != nil {
		log.Fatalf("Error unmarshaling response body: %v", err)
	}
	// 打印响应状态码和响应体
	fmt.Printf("Response Status: %s\n", resp.Status)
	fmt.Printf("Response Body: %s\n", body)
	// 处理表单数据
	c.JSON(http.StatusOK, gin.H{
		"Response Body:": m,
		"当前时间":           nowFormatted,
	})
}
